﻿let connection = null;

setupConnection = () => {
    connection = new signalR.HubConnectionBuilder()
        .withUrl("/counthub")
        .build();

    connection.on("receiveUpdate", (update) => {
        const resultDiv = document.getElementById("result");

        resultDiv.innerHTML = update;
    });

    connection.on("someFunc", (obj) => {
        const resultDiv = document.getElementById("result");

        resultDiv.innerHTML = "Someone called,paramters:" + obj.name;
    });

    connection.on("finished", () => {
        connection.stop();
        const resultDiv = document.getElementById("result");

        resultDiv.innerHTML = "Finished";
    });

    connection.start(err => console.log(err.toString()))
        .catch(err => console.log(err.toString()));
}

setupConnection();

document.getElementById("submit").addEventListener("click", e => {
    e.preventDefault();
    fetch("/api/count", {
        method: "POST",
        headers: {
            "content-type": "application/json"
        },
        body: JSON.stringify({ id: connection })
    }).then(response => response.text())
        .then(id => connection.invoke("GetLatestCount", id));
});